//
//  CarFactoyTypeVC.m
//  New_Runway
//
//  Created by mack on 2018/2/6.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "CarFactoyTypeVC.h"
#import "NRWCarCarListCell.h"
#import "NRWCarHomeBannerModel.h"
#import "NRWCarHomeNoticeModel.h"
#import "NRWCarListsModel.h"
#import "CarDetailMainVC.h"
#import "BuyCarTopview.h"

#import "DefaultSortView.h"
#import "AllKindOfCarVC.h"
#import "SectionSliderVC.h"
#import "CarFilterVC.h"
#import "CarStateSearchVC.h"
#import "LYSideslipCell.h"
#import "TargetString.h"
#import "NRWCarListRejectCell.h"
#import "NRWCarRefuseVC.h"
#import "IamgeFactory.h"
#import "NRWCarSearchView.h"
#import "NRWCarLongPressView.h"



@interface CarFactoyTypeVC ()<UITableViewDelegate,
UITableViewDataSource,
UIGestureRecognizerDelegate,
LYSideslipCellDelegate,
UITextFieldDelegate,
NRWCarSearchViewDelegate>
@property(nonatomic, strong) UITableView *tableview;
@property (assign, nonatomic) NSInteger pageNo;
@property (nonatomic, strong) NSMutableArray *carArray;
@property (nonatomic, strong) BuyCarTopview *topview;
@property (nonatomic, strong) NSMutableDictionary *params;
@property (nonatomic, strong) DefaultSortView *defaultView;
@property (nonatomic, assign) BOOL isShow;
@property (nonatomic, strong) NSIndexPath *seleIndex;
@property (nonatomic, strong) NSIndexPath *modelSeleIndexPath;
@property (nonatomic, strong) NSIndexPath *seriesSeleIndexPath;
@property (nonatomic, strong) NSMutableDictionary *filterDic;
@property (nonatomic, strong) NSMutableDictionary *indexDic;
@property (nonatomic, assign) NSInteger isdeledate;
@property (nonatomic, strong) UIView *instructView;
@property (nonatomic, assign)BOOL ifSelectedOne;//是否选中
@property (nonatomic, assign)BOOL ifSelectedTwo;//是否选中
@property (nonatomic, assign)BOOL ifSelectedThree;//是否选中
@property (nonatomic, assign)BOOL ifSelectedFour;//是否选中
@property (nonatomic, strong) NSMutableDictionary *StateDic;
@property (nonatomic, assign) BOOL isWhich;
@property (nonatomic, copy) NSString *fromPrice;
@property (nonatomic, copy) NSString *toPrice;
@property (nonatomic, strong) NSIndexPath *reloadPath;
@property (nonatomic, copy) NSString *carSaleState;
@property (nonatomic, copy) NSString *carDetectState;
@property (nonatomic, copy) NSString *carOrderState;
@property (nonatomic, copy) NSString *stateType;
@property (nonatomic, copy) NSString *price;
@property (nonatomic, strong) NSNumber *carMileage;
@property (nonatomic, copy) NSString *date;
@property (nonatomic, copy) NSString *carTitle;
@property (nonatomic, copy) NSString *carLicenceState;
@property (copy, nonatomic) NSString *carVIN6;

@property (strong, nonatomic) NRWCarSearchView *searchView;
@property (strong, nonatomic) NSMutableDictionary *contentOffset;
@property (strong, nonatomic) NRWCarLongPressView *longView;//长按弹框

@end

@implementation CarFactoyTypeVC
-(NSMutableDictionary *)indexDic{
    if (!_indexDic) {
        _indexDic = [[NSMutableDictionary alloc] init];
    }
    return _indexDic;
}
-(NSMutableDictionary *)contentOffset{
    if (!_contentOffset) {
        _contentOffset = [[NSMutableDictionary alloc] init];
    }
    return _contentOffset;
}
-(NSMutableArray *)carArray{
    if (!_carArray) {
        _carArray = [[NSMutableArray alloc] init];
    }
    
    return _carArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.fromPrice = self.toPrice = @"";
    self.pageNo = 1;
    [self initTableview];
    [self setupSearchBar];
    [self setdicValueForKey];
    
    [self.view addSubview:self.topview];
    self.isShow = NO;
    [self.view addSubview:self.defaultView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(brandSearch:)name:@"BrandSearchDesk" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(seleletedKindOfCarIndexPath:)name:@"SELEINDEXPATHDESK" object:nil]; 
    [self.indexDic setObject:@(INTMAX_MAX) forKey:@"threeIndex"];
    [self.indexDic setObject:@(INTMAX_MAX) forKey:@"fourIndex"];
    [self.indexDic setObject:@(INTMAX_MAX) forKey:@"fiveIndex"];
    self.isdeledate = 0;
    if ([self.type isEqualToString:kCarNoLibary]) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString *intruct = [ user objectForKey:@"instruct"];
        if ([intruct isEqualToString:@"1"]) {
        }else{
            self.instructView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.6];
        }
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(inputAndOutFactory:) name:@"FactorySuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setCarPrice:) name:@"setPrice" object:nil];
    [self addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];

}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"contentOffset"]) {
        [self.longView removeFromSuperview];
    }
}
- (void)setupSearchBar {
    
    if (!self.isShowSearchVIN) {
//        return;
    }
    
    _searchView = [[NRWCarSearchView alloc] initWithPlaceHold:@"请输入VIN码后六位进行查询" leftImageName:@"icon_search_vin" rightImageName:@"icon_delete_vin"];
    _searchView.delegate_custom = self;
    _searchView.delegate = self;
    self.navigationBarView.addSubview(_searchView);
    
    _searchView.layer.cornerRadius = 13;
    _searchView.layer.masksToBounds = YES;
    [_searchView addTarget:self action:@selector(searchViewTextChange:) forControlEvents:UIControlEventEditingChanged];
    
    [_searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.navigationBarView.mas_left).offset(62);
        make.right.equalTo(self.navigationBarView.mas_right).offset(-62);
        make.height.equalTo(@27);
        make.bottom.equalTo(self.navigationBarView.mas_bottom).offset(-8);
    }];
}

-(void)inputAndOutFactory:(NSNotification *)info{
    self.reloadPath = info.object;
    self.stateType = info.userInfo[@"type"];
    if ([self.stateType isEqualToString:@"carSaleState"]) {
        self.carSaleState = info.userInfo[@"value"];
    }else if ([self.stateType isEqualToString:@"carDetectState"]){
        self.carDetectState = info.userInfo[@"value"];
        
    }else if ([self.stateType isEqualToString:@"carOrderState"]){
        if ([self.type isEqualToString:kCarOrder]){
            [self.carArray removeObjectAtIndex:self.reloadPath.row];
            if (self.carArray.count == 0) {
                self.pageNo = 1;
                [self.params setObject:@(self.pageNo) forKey:@"pageIndex"];
                [self loadCarList];
                
            }
        }else{
            self.carOrderState = info.userInfo[@"value"];
        }
        
    }else{
        [self.carArray removeObjectAtIndex:self.reloadPath.row];
        if (self.carArray.count == 0) {
            self.pageNo = 1;
            [self.params setObject:@(self.pageNo) forKey:@"pageIndex"];
            [self loadCarList];
  
        }
    }
    [self.tableview reloadData];

}
-(void)setCarPrice:(NSNotification *)info{
    self.reloadPath = info.object;
    self.stateType = info.userInfo[@"type"];
    self.price = info.userInfo[@"value"];
    if ([self.stateType isEqualToString:@"CarEdit"]) {
        self.date = info.userInfo[@"date"];
        self.carTitle = info.userInfo[@"carTitle"];
        self.carMileage = info.userInfo[@"carMileage"];
        self.carLicenceState = info.userInfo[@"carLicenceState"];
    }
    
    [self.tableview reloadData];

}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
}
-(UIView *)instructView{
    if (!_instructView) {
        _instructView = [[UIView alloc] init];
        [self.view addSubview:_instructView];
        kSelfWeak;
        [_instructView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.top.equalTo(weakSelf.view);
        }];
        UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc]initWithTarget:self     action:@selector(tapAction:)];
        tap.numberOfTapsRequired =1;
        tap.numberOfTouchesRequired =1;
        [_instructView addGestureRecognizer:tap];
        
        UIImageView *image = [[UIImageView alloc] init];
        image.image = [UIImage imageNamed:@"操作指示"];
        [_instructView addSubview:image];
        [image mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.view).mas_offset(weakSelf.navH + 60);
            make.right.equalTo(weakSelf.view.mas_right).mas_offset(-20);
        }];

    }
    return _instructView;
}
-(void)tapAction:(UITapGestureRecognizer *)tap
{
    NSString *isInstruct= @"1";
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setObject:isInstruct forKey:@"instruct"];
    [self.instructView removeFromSuperview];
}
-(void)setdicValueForKey{
    if ([self.userRole isEqualToString:kUserRoleShopStaff]) {//车商
        _params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NRWCarUser sharedUser].marketId,@"marketId",@(15),@"pageSize",@(self.pageNo),@"pageIndex",[NRWCarUser sharedUser].shopId,@"shopId",nil];
    }else if ([self.userRole isEqualToString:kUserRoleMarketStaff]){//市场员工
        _params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NRWCarUser sharedUser].marketId,@"marketId",@(15),@"pageSize",@(self.pageNo),@"pageIndex",[NRWCarUser sharedUser].userId,@"userId",nil];
    }else{//市场管理员
        _params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NRWCarUser sharedUser].marketId,@"marketId",@(15),@"pageSize",@(self.pageNo),@"pageIndex",nil];

    }

    [self.params setValue:@"DESC" forKey:@"orderMode"];
    
    if ([self.type isEqualToString:kCarInLibary]) {
        [_params setObject:@(20) forKey:@"carStockState"];
        [self.params setValue:@"CAR_STOCK_TIME" forKey:@"orderColunm"];

        self.navigationBarView.titleLabel.text = @"在库车辆";
    }else if ([self.type isEqualToString:kCarOutLibary]){
        [_params setObject:@(40) forKey:@"carStockState"];
        [self.params setValue:@"SALE_CREATE_TIME" forKey:@"orderColunm"];

        self.navigationBarView.titleLabel.text = @"出库车辆";

    }else if ([self.type isEqualToString:kCarOrder]){
        self.navigationBarView.titleLabel.text = @"已预定";
        [self.params setValue:@"ORDER_CREATE_TIME" forKey:@"orderColunm"];

        [_params setObject:@(1) forKey:@"carOrderState"];
    }else if ([self.type isEqualToString:kCarNoLibary]){
         [_params setObject:@(0) forKey:@"carStockState"];
        [self.params setValue:@"CAR_CREATE_TIME" forKey:@"orderColunm"];

        self.navigationBarView.titleLabel.text = @"未完成入库";

    }else if ([self.type isEqualToString:kCarInLibaryApplying]){
        self.navigationBarView.titleLabel.text = @"入库申请中";
        [_params setObject:@(10) forKey:@"carStockState"];
        [self.params setValue:@"CAR_STOCK_TIME" forKey:@"orderColunm"];

    }else if ([self.type isEqualToString:kCarOutLibaryApplying]){
        self.navigationBarView.titleLabel.text = @"出库申请中";
        [_params setObject:@(30) forKey:@"carStockState"];
        [self.params setValue:@"CAR_STOCK_TIME" forKey:@"orderColunm"];

    }
    [self loadCarList];
    self.seleIndex = [NSIndexPath indexPathForRow:0 inSection:0];
    self.modelSeleIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    self.seriesSeleIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.defaultView updateSelected];

}
-(BuyCarTopview *)topview{
    
    if (!_topview) {
        _topview = [[[NSBundle mainBundle] loadNibNamed:@"BuyCarTopview" owner:self options:nil]lastObject];
        [_topview.filterButton setTitle:@"状态" forState:UIControlStateNormal];
        kSelfWeak;
        _topview.Clickback = ^(NSInteger index) {

            [weakSelf.view endEditing:YES];
            
            if (index == 1) {
                weakSelf.isShow = !weakSelf.isShow;
                [weakSelf defaultViewAnimation:weakSelf.isShow];
            }else if (index == 2){
                AllKindOfCarVC *carVC = [[AllKindOfCarVC alloc] init];
                carVC.isDesk = YES;
                carVC.Allback = ^(NSIndexPath *index) {
                    [weakSelf.params removeObjectForKey:@"brandId"];
                    [weakSelf.params removeObjectForKey:@"modelId"];
                    [weakSelf.params removeObjectForKey:@"seriesId"];
                    weakSelf.pageNo = 1;
                    [weakSelf.params setObject:@(weakSelf.pageNo) forKey:@"pageIndex"];
                    [weakSelf loadCarList];
                    weakSelf.seleIndex = index;

                };
                carVC.selectedIndexPath = weakSelf.seleIndex;
                carVC.modelSeleIndexPath = weakSelf.modelSeleIndexPath;
                carVC.seriesSeleIndexPath = weakSelf.seriesSeleIndexPath;
                [weakSelf.navigationController pushViewController:carVC animated:YES];
            }else if (index == 3){
                SectionSliderVC *sliderVc = [[SectionSliderVC alloc] init];
                sliderVc.block = ^(NSString *fromPrice, NSString *toPrice, BOOL isWhich) {
                    [weakSelf.params setObject:fromPrice forKey:@"fromRetailPrice"];
                    [weakSelf.params setObject:toPrice forKey:@"toRetailPrice"];
                    weakSelf.pageNo = 1;
                    [weakSelf.params setObject:@(weakSelf.pageNo) forKey:@"pageIndex"];
                    [weakSelf loadCarList];
                    weakSelf.isWhich = isWhich;
                    weakSelf.fromPrice = fromPrice;
                    weakSelf.toPrice = toPrice;
                };
                sliderVc.isWhich = weakSelf.isWhich;
                sliderVc.fromPrice = weakSelf.fromPrice;
                sliderVc.toPrice = weakSelf.toPrice;
                
                [weakSelf.navigationController pushViewController:sliderVc animated:YES];
                
            }else if (index == 4){
                
                CarFilterVC *filterVC = [[CarFilterVC alloc] init];
                filterVC.isBuyCar = NO;
                filterVC.searchBlock = ^(NSMutableDictionary *searchDic, NSMutableDictionary *indexPathDic) {
                    [weakSelf.params addEntriesFromDictionary:searchDic];
                    weakSelf.filterDic = searchDic;
                    weakSelf.indexDic = indexPathDic;
                    weakSelf.pageNo = 1;
                    [weakSelf.params setObject:@(weakSelf.pageNo) forKey:@"pageIndex"];
                    [weakSelf loadCarList];
                };
                filterVC.allDataDic = weakSelf.filterDic;
                filterVC.selectedDic = weakSelf.indexDic;
                [weakSelf.navigationController pushViewController:filterVC animated:YES];
            }else if (index == 5){
                
                CarStateSearchVC *stateVC = [[CarStateSearchVC alloc] init];
                stateVC.type = weakSelf.type;
                stateVC.stateBlock = ^(NSMutableDictionary *stateDic) {
                    [weakSelf.params addEntriesFromDictionary:stateDic];
                    weakSelf.pageNo = 1;
                    [weakSelf.params setObject:@(weakSelf.pageNo) forKey:@"pageIndex"];
                    [weakSelf loadCarList];
                    weakSelf.ifSelectedOne = [weakSelf.params[@"carBargainPriceState"] boolValue];
                    weakSelf.ifSelectedTwo = [weakSelf.params[@"carOrderState"] boolValue];
                    weakSelf.ifSelectedThree = [weakSelf.params[@"carAuthState"] boolValue];
                    if ( [weakSelf.params[@"carStockState"] integerValue] == 1) {
                        weakSelf.ifSelectedFour = YES;
                    }else{
                        weakSelf.ifSelectedFour = NO;
                    }
                   
                    weakSelf.StateDic = stateDic;
                };
                stateVC.ifSelectedOne = weakSelf.ifSelectedOne;
                stateVC.ifSelectedTwo = weakSelf.ifSelectedTwo;
                stateVC.ifSelectedThree = weakSelf.ifSelectedThree;
                stateVC.ifSelectedFour = weakSelf.ifSelectedFour;
                stateVC.StateDic = weakSelf.StateDic;
                [weakSelf.navigationController pushViewController:stateVC animated:YES];
            }
        };
        _topview.frame = CGRectMake(0, self.navH, Screen_width, 40);
        _topview.layer.shadowOpacity = 0.3;
        _topview.layer.shadowColor = [UIColor grayColor].CGColor;
        _topview.layer.shadowRadius = 3;
        _topview.layer.shadowOffset = CGSizeMake(1,1);
        [self.navigationBarView bringSubviewToFront:self.view];
    }
    return _topview;
}
-(void)initTableview{
    kSelfWeak;
    self.tableview = [[UITableView alloc] init];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    _tableview.estimatedRowHeight = 0;
    _tableview.estimatedSectionHeaderHeight = 0;
    _tableview.estimatedSectionFooterHeight = 0;
    if (@available(iOS 11.0, *)) {
        self.tableview.contentInsetAdjustmentBehavior = UIApplicationBackgroundFetchIntervalNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = false;
    }
    self.tableview.backgroundColor = MAIN_COLOR();
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableview registerNib:[UINib nibWithNibName:@"NRWCarCarListCell" bundle:nil] forCellReuseIdentifier:@"NRWCarCarListCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"NRWCarListRejectCell" bundle:nil] forCellReuseIdentifier:@"NRWCarListRejectCell"];
    self.tableview.mj_header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downPullRefresh)];
    self.tableview.mj_footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upPullLoadMore)];
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).mas_equalTo(self.navH + 40);
        make.bottom.equalTo(weakSelf.view);
        make.left.right.equalTo(weakSelf.view);
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    [self.view endEditing:YES];
    
    [self.longView removeFromSuperview];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 110;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.carArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    Result *rt = self.carArray[indexPath.row];
    if (self.reloadPath == indexPath) {
        if ([self.stateType isEqualToString:@"carSaleState"]) {
            rt.carSaleState = [self.carSaleState integerValue];
        }else if ([self.stateType isEqualToString:@"carDetectState"]){
            rt.carDetectState = [self.carDetectState integerValue];
        }else if ([self.stateType isEqualToString:@"carOrderState"]){
            rt.carOrderState = [self.carOrderState integerValue];
        }else if ([self.stateType isEqualToString:@"price"]){
            rt.carRetailPrice = [self.price doubleValue];
        }else if ([self.stateType isEqualToString:@"carBargainPriceState"]){
            rt.carBargainPriceState = 1;
        }else if ([self.stateType isEqualToString:@"CarEdit"]){
            rt.carRetailPrice = [self.price doubleValue];
            rt.carTitle = self.carTitle;
            rt.carMileage = self.carMileage;
            rt.carLicenceDate = [NRWCarTurnTime timeSwitchTimestamp:self.date andFormatter:@"yyyy-MM"] * 1000;
            rt.carLicenceState = [self.carLicenceState integerValue];
        }
    }
    if (rt.carStockState == 1) {
        NRWCarListRejectCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NRWCarListRejectCell"];
        cell.index = indexPath;
        cell.carModel = rt;
        cell.delegate = self;
        return cell;
    }
    NRWCarCarListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NRWCarCarListCell"];
    cell.type = self.type;
    cell.carModel = rt;
    cell.delegate = self;
    if ([self.type isEqualToString:kCarInLibary]) {
        if (cell.gestureRecognizers.count == 0) {
            UILongPressGestureRecognizer * longPressGesture =[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(cellLongPress:)];
            longPressGesture.minimumPressDuration = 1.0f;//设置长按 时间
            [cell addGestureRecognizer:longPressGesture];
        }
    }
    
    
    return cell;
}

-(void)cellLongPress:(UILongPressGestureRecognizer *)longRecognizer{
    
    if (longRecognizer.state==UIGestureRecognizerStateBegan) {
        [self becomeFirstResponder];
        [self.longView removeFromSuperview];
        CGPoint location = [longRecognizer locationInView:self.tableview];
        NSIndexPath *indexPath = [self.tableview indexPathForRowAtPoint:location];
        NRWCarCarListCell *cell = [self.tableview cellForRowAtIndexPath:indexPath];
        Result *rt = self.carArray[indexPath.row];
        self.longView = [[NRWCarLongPressView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)];
        self.longView.model = rt;
        [cell.contentView addSubview:_longView];
        
    }
    
}

- (BOOL)sideslipCell:(LYSideslipCell *)sideslipCell canSideslipRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.type isEqualToString:kCarNoLibary]) {
        return YES;
    }
    return NO;
    
}

- (NSArray<LYSideslipCellAction *> *)sideslipCell:(LYSideslipCell *)sideslipCell editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    kSelfWeak;
    LYSideslipCellAction *rowAction = [LYSideslipCellAction rowActionWithStyle:LYSideslipCellActionStyleNormal title:@"删除" handler:^(LYSideslipCellAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
         Result *rt = weakSelf.carArray[indexPath.row];
        [weakSelf deleteCarFormList:rt.carId withIndex:indexPath.row];
        [sideslipCell hiddenSideslip];

    }];
 
        return @[rowAction];


}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CarDetailMainVC *carDVC = [[CarDetailMainVC alloc] init];
    carDVC.selIndex = indexPath;
//    if ([self.type isEqualToString:kCarOutLibary] || [self.type isEqualToString:kCarOutLibaryApplying]) {
//        
//        carDVC.isShowR = NO;
//    }else{
//   
//        carDVC.isShowR = YES;
//    }
    [self willChangeValueForKey:@"contentOffset"];
    [self.contentOffset  setValue:@(1) forKey:@"contentOffset"];
    [self didChangeValueForKey:@"contentOffset"];
    
    carDVC.isShowR = !([self.type isEqualToString:kCarOutLibary] || [self.type isEqualToString:kCarOutLibaryApplying]);
    carDVC.isShowShare = [self.type isEqualToString:kCarInLibary];
    Result *rt = self.carArray[indexPath.row];
    carDVC.carID = rt.carId;
    carDVC.modelID = rt.modelId;
    carDVC.isReject = rt.carStockState;
    [self.navigationController pushViewController:carDVC animated:YES];
    
    
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self willChangeValueForKey:@"contentOffset"];
    [self.contentOffset  setValue:@(scrollView.contentOffset.y) forKey:@"contentOffset"];
    [self didChangeValueForKey:@"contentOffset"];
}
-(void)downPullRefresh{
    self.pageNo = 1;
    [_params setObject:@(self.pageNo) forKey:@"pageIndex"];
    [self loadCarList];
}
-(void)upPullLoadMore{
    self.pageNo += 1;
    [_params setObject:@(self.pageNo) forKey:@"pageIndex"];
    [self loadCarList];
    
}

-(void)loadCarList{
    
    [self loadCarNumRequest];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",Api,carListsApi];
    [SVProgressHUD show];
    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:_params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        if (self.pageNo == 1) {
            [self.carArray removeAllObjects];
        }
        NSArray *noticeArr = response[@"result"];
        for (NSDictionary *dic in noticeArr) {
            Result *rt = [Result mj_objectWithKeyValues:dic];
            [self.carArray addObject:rt];
        }
        if (self.carArray.count == 0) {
            [self.tableview addDefaultViewWithText:@"暂无数据" defaultImageType:DefaultImageTypeNoData];
        }else{
            [self.tableview removeDefaultView];
        }
        self.stateType = @"";
        [self.tableview reloadData];
        [self endRefresh];
        [SVProgressHUD dismiss];
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"加载数据失败" duration:2.0 withRemindId:remindFail];
        [self endRefresh];
        [SVProgressHUD dismiss];
        
    }];
}

- (void)loadCarNumRequest {
    
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@", Api, @"/controller/getCarNum"] refreshRequest:NO cache:NO params:self.params progressBlock:nil successBlock:^(id response) {
        
        NSDictionary *result = response[@"result"];
        
        if ([result isKindOfClass:[NSDictionary class]]) {
         
            NSNumber *string = result[@"total"];
            
            if ([string isKindOfClass:[NSNumber class]]) {
                
                if (string.integerValue == 0) {
                    return;
                } else {
                    self.tableview.tableHeaderView = [self getTableViewHeaderWithCarTotalStr:[NSString stringWithFormat:@"%@", string]];
                }
            }
        }
 
    } failBlock:^(NSError *error) {
        
    }];
}

- (UIView *)getTableViewHeaderWithCarTotalStr:(NSString *)carTotalStr {
    
    UIView *headerView = DPView().setBackgroundColor(getColorFromString(@"F5F5F5"));
    
    UILabel *label = DPLabel().setTextColor(getColorFromString(@"#989898")).setFont(kPingFangRegular11());
    
    NSString *string = [NSString stringWithFormat:@"共有%@辆%@", carTotalStr, self.navigationBarView.titleLabel.text];
    
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
    
    NSRange carTotalNumrange = [string rangeOfString:carTotalStr];
    
    [attrString setAttributes:@{NSForegroundColorAttributeName: getColorFromString(@"#FF6816")} range:carTotalNumrange];
    
    label.attributedText = attrString;
    
    headerView.addSubview(label);
    
    label.frame = CGRectMake(16, 0, Screen_width - 32, 20);
    
    headerView.frame = CGRectMake(0, 0, Screen_width, 20);
    
    return headerView;
}


-(void)endRefresh{
    [self.tableview.mj_header endRefreshing];
    [self.tableview.mj_footer endRefreshing];
    
}

-(DefaultSortView *)defaultView{
    if (!_defaultView) {
        _defaultView = [[DefaultSortView alloc] init];
        _defaultView.type = self.type;
        _defaultView.frame = CGRectMake(0, self.navH + 40, Screen_width, 0);
        _defaultView.userInteractionEnabled = YES;
        UITapGestureRecognizer * PrivateLetterTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAvatarView:)];
        PrivateLetterTap.numberOfTouchesRequired = 1; //手指数
        PrivateLetterTap.numberOfTapsRequired = 1; //tap次数
        PrivateLetterTap.delegate = self;
        [_defaultView addGestureRecognizer:PrivateLetterTap];
        kSelfWeak;
        _defaultView.selectedBlock = ^(NSInteger index) {
            [weakSelf defaultViewAnimation:NO];
            weakSelf.isShow = NO;
            if (index == 0) {
                
                if ([weakSelf.type isEqualToString:kCarInLibary]  || [weakSelf.type isEqualToString:kCarInLibaryApplying]  || [weakSelf.type isEqualToString:kCarOutLibaryApplying]) {
                    [weakSelf.params setValue:@"CAR_STOCK_TIME" forKey:@"orderColunm"];

                }else if ([weakSelf.type isEqualToString:kCarOutLibary]){
                    [weakSelf.params setValue:@"SALE_CREATE_TIME" forKey:@"orderColunm"];

                }else if ([weakSelf.type isEqualToString:kCarOrder]){
                    [weakSelf.params setValue:@"ORDER_CREATE_TIME" forKey:@"orderColunm"];

                }else if ([weakSelf.type isEqualToString:kCarNoLibary]){
                    [weakSelf.params setValue:@"CAR_CREATE_TIME" forKey:@"orderColunm"];

                }
                [weakSelf.params setValue:@"DESC" forKey:@"orderMode"];
                
            }else if (index == 1){
                
                if ([weakSelf.type isEqualToString:kCarInLibary]  || [weakSelf.type isEqualToString:kCarInLibaryApplying] || [weakSelf.type isEqualToString:kCarOutLibaryApplying] ) {
                    [weakSelf.params setValue:@"CAR_STOCK_TIME" forKey:@"orderColunm"];

                }else if ([weakSelf.type isEqualToString:kCarOutLibary]){
                    [weakSelf.params setValue:@"SALE_CREATE_TIME" forKey:@"orderColunm"];

                }else if ([weakSelf.type isEqualToString:kCarOrder]){
                    [weakSelf.params setValue:@"ORDER_CREATE_TIME" forKey:@"orderColunm"];

                }else if ([weakSelf.type isEqualToString:kCarNoLibary]){
                    [weakSelf.params setValue:@"CAR_CREATE_TIME" forKey:@"orderColunm"];
                    
                }
                [weakSelf.params setValue:@"ASC" forKey:@"orderMode"];
            }else if (index == 2){
                [weakSelf.params setValue:@"DESC" forKey:@"orderMode"];
                [weakSelf.params setValue:@"CAR_RETAIL_PRICE" forKey:@"orderColunm"];
                
            }else if (index == 3){
                [weakSelf.params setValue:@"ASC" forKey:@"orderMode"];
                [weakSelf.params setValue:@"CAR_RETAIL_PRICE" forKey:@"orderColunm"];
                
            }else if (index == 4){
                [weakSelf.params setValue:@"DESC" forKey:@"orderMode"];
                [weakSelf.params setValue:@"CAR_LICENCE_DATE" forKey:@"orderColunm"];
                
            }else if (index == 5){
                [weakSelf.params setValue:@"ASC" forKey:@"orderMode"];
                [weakSelf.params setValue:@"CAR_MILEAGE" forKey:@"orderColunm"];
                
            }
            weakSelf.pageNo = 1;
            [weakSelf.params setObject:@(weakSelf.pageNo) forKey:@"pageIndex"];
            [weakSelf loadCarList];
            
        };
    }
    return _defaultView;
}
- (void)tapAvatarView: (UITapGestureRecognizer *)gesture{
    
    [self defaultViewAnimation:NO];
    self.isShow = NO;
}

-(void)defaultViewAnimation:(BOOL)isshow{
    if (isshow == YES) {
        _defaultView.frame = CGRectMake(0, self.navH + 40, Screen_width, Screen_height - self.navH - 40);
        
        [UIView animateWithDuration:0.5 animations:^{
            _defaultView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.4];
            _defaultView.tableview.frame = CGRectMake(0, 0, Screen_width, 300);
        } completion:^(BOOL finished) {
            
        }];
    }else{
        [UIView animateWithDuration:0.5 animations:^{
            _defaultView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0];
            _defaultView.tableview.frame = CGRectMake(0, 0, Screen_width, 0);
            
        } completion:^(BOOL finished) {
            _defaultView.frame = CGRectMake(0, self.navH + 40, Screen_width, 0);
            
        }];
    }
    
}
-(void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    [self defaultViewAnimation:NO];
    self.isShow = NO;
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {//判断如果点击的是tableView的cell，就把手势给关闭了
        return NO;//关闭手势
    }//否则手势存在
    return YES;
}

-(void)brandSearch:(NSNotification *)info{
    NSDictionary *dic = info.userInfo;
    [self.params setValue:dic[@"brandId"] forKey:@"brandId"];
    [self.params setValue:dic[@"seriesId"] forKey:@"modelId"];
    [self.params setValue:dic[@"modelId"] forKey:@"seriesId"];
    self.pageNo = 1;
    [self.params setObject:@(self.pageNo) forKey:@"pageIndex"];
    [self loadCarList];
}
-(void)seleletedKindOfCarIndexPath:(NSNotification *)info{
    NSDictionary *dic = info.userInfo;
    self.seleIndex = dic[@"brandIndexPath"];
    self.modelSeleIndexPath = dic[@"modelIndexPath"];
    self.seriesSeleIndexPath = dic[@"seriesIndexPath"];
    
}
-(void)deleteCarFormList:(NSString *)carId withIndex:(NSInteger)index{
    NSString *url = [NSString stringWithFormat:@"%@%@",Api,carDeleteApi];
    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:@{@"carId":carId,@"userId":[NRWCarUser sharedUser].userId} progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
       
    } successBlock:^(id response) {
        if ([response[@"code"] isEqual:@1]) {
            [self.carArray removeObjectAtIndex:index];
            [ShowMessage showHintMessage:@"删除成功!" duration:2.0 withRemindId:remindSuccess];
            if (self.carArray.count == 0) {
                self.pageNo = 1;
                [self.params setObject:@(self.pageNo) forKey:@"pageIndex"];
                [self loadCarList];
            }
            self.stateType = @"";
            [self.tableview reloadData];
        }else{
            [ShowMessage showHintMessage:@"删除失败" duration:2.0 withRemindId:remindFail];

        }
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
    }];
    
    
}
- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    NSIndexPath *index = userInfo[@"index"];
    Result *rt = self.carArray[index.row];
    NRWCarRefuseVC *refuseVC = [[NRWCarRefuseVC alloc] init];
    refuseVC.carId  = rt.carId;
    [self.navigationController pushViewController:refuseVC animated:YES];
}

-(void)leftItemClick{
    [self.navigationController popViewControllerAnimated:YES];
    [IamgeFactory reset];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (textField.text.length != 6) {
        [ShowMessage showHintMessage:@"请输入VIN码后六位" duration:2 withRemindId:remindWarning];
        return NO;
    }
    
    [self.params setObject:textField.text forKey:@"carVin6"];
    
    [self downPullRefresh];
    
    return YES;
}

- (void)searchView:(NRWCarSearchView *)searchView rightBtnDidClick:(UIButton *)sender {
    
    if (self.params[@"carVin6"] == nil) {//如果搜索条件为空, 点击删除按钮不与响应, 减少不必须请求
        return;
    }
    
    [self.params removeObjectForKey:@"carVin6"];
    
    self.searchView.text = nil;
    
    [self downPullRefresh];
}

- (void)searchViewTextChange:(UITextField *)sender {
    
    if (_searchView.text.length > 6) {
        
        _searchView.text = [_searchView.text substringToIndex:6];
    }
}
-(void)dealloc{
    [self removeObserver:self forKeyPath:@"contentOffset"];
}
@end
